package com.baili.service.productionorder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baili.dao.operater.OperateDao;
import com.baili.dao.productionorder.ProductionOrderDao;
import com.baili.dao.user.UserDao;
import com.baili.dto.ProductOrder;
import com.baili.util.StringUtil;

/**
 * @author iceX
 * @version 创建时间：2016年3月25日 上午11:31:11
 * @Name: ProductionOrderServiceImpl.java
 */
@Service
public class ProductionOrderServiceImpl implements ProductionOrderService {

	@Autowired
	private ProductionOrderDao productionOrderDao;

	@Autowired
	private OperateDao operateDao;

	@Autowired
	private UserDao userDao;

	@Override
	public List<Map<String, Object>> getProductionOrderList(
			ProductOrder productOrder) {

		List<Map<String, Object>> proLst = productionOrderDao
				.getProLst(productOrder);

		if (proLst != null && proLst.size() > 0) {

			for (Map<String, Object> proMap : proLst) {
				//未开工任务记数器
				int unfinishedCount = 0;
				//加工中任务记数器
				int machiningCount = 0;
				//已完成任务记数器
				int finishedCount = 0;
				//超期任务记数器
				int outTimeAllCount = 0;
				
				productOrder.setScheduleNo(proMap.get("scheduleNo").toString());

				List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();

				if (productOrder.getApprUserId() > 0) {
					// 审批列表 获取生产通知单信息
					lst = productionOrderDao
							.getApprProductionOrderList(productOrder);

				} else {
					// 查看列表 获取生产通知单信息
					lst = productionOrderDao
							.getProductionOrderList(productOrder);
				}

				for (Map<String, Object> map : lst) {

					int notStartedCount = 0;

					int alreadyCompletedCount = 0;

					int outTimeCount = 0;

					productOrder
							.setScheduleNo(map.get("scheduleNo").toString());

					productOrder.setProductCode(map.get("productCode")
							.toString());

					List<Map<String, Object>> roundLst = new ArrayList<Map<String, Object>>();

					if (productOrder.getApprUserId() > 0) {
						// 审批列表 获取生产通知单信息
						roundLst = productionOrderDao
								.getApprProductorderList(productOrder);
					} else {
						// 查看列表 获取生产通知单信息
						roundLst = productionOrderDao
								.getProductorderList(productOrder);
					}

					for (Map<String, Object> roundMap : roundLst) {

						String state = roundMap.get("state").toString();
						
						String kzType = roundMap.get("kzType").toString();

						Date d_overTime = (Date) map.get("overTime");

						if ((new Date()).getTime() - d_overTime.getTime() > 0) {

							outTimeCount++;

						} 

						if (!state.equals("5")) {

							if (state.equals("1") && (kzType.equals("0") || kzType.equals("1"))) {

								notStartedCount = notStartedCount + 1;

							}
						} else if(state.equals("5") && (kzType.equals("0") || kzType.equals("2"))){

							alreadyCompletedCount = alreadyCompletedCount + 1;

						}
					}
					
					if (roundLst.size() == alreadyCompletedCount) {

						map.put("status", 3);
						
						finishedCount = finishedCount + 1;
						
					} else if (roundLst.size() == notStartedCount) {

						map.put("status", 1);
						
						unfinishedCount = unfinishedCount + 1;
						
					}  else {

						map.put("status", 2);
						
						machiningCount = machiningCount + 1;

					}
					
					if (outTimeCount > 0) {
						
//						map.put("status", 4);
						
						outTimeAllCount = outTimeAllCount + 1;
						
					}

					if (map.get("productName").toString().contains("帮面")) {

						map.put("processName", "帮面生产");

					} else if (map.get("productName").toString().contains("中底")) {

						map.put("processName", "中底生产");

					} else if (map.get("productName").toString()
							.contains("成型底")) {

						map.put("processName", "成型底生产");

					} else if (map.get("productName").toString()
							.equals(map.get("finishedProductName").toString())) {

						map.put("processName", "成品生产");
					}
				}
				//判断如果有一个超期的，那么全部超期
				if (lst.size() == finishedCount) {

					proMap.put("status", 3);
					//如果以上都不通过，则为加工中状态
				}else if(outTimeAllCount > 0) {
					
					proMap.put("status", 4);
					//判断如果所有都是未开工，则显示未开工状态
				}  else if (lst.size() == unfinishedCount) {

					proMap.put("status", 1);
					//判断如果所有都已完工，则显示已完工状态
				} else {

					proMap.put("status", 2);
				}

				proMap.put("prolst", lst);
			}
		}

		return proLst;
	}

	@Override
	public List<Map<String, Object>> getProductionOrderListArp(
			ProductOrder productOrder) {

		List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();

		if (productOrder.getApprUserId() > 0) {
			// 审批列表 获取生产通知单信息
			lst = productionOrderDao.getApprProductionOrderList(productOrder);

		} else {
			// 查看列表 获取生产通知单信息
			lst = productionOrderDao.getProductionOrderList(productOrder);
		}

		for (Map<String, Object> map : lst) {

			int notStartedCount = 0;

			int alreadyCompletedCount = 0;

			int outTimeCount = 0;

			productOrder.setScheduleNo(map.get("scheduleNo").toString());

			productOrder.setProductCode(map.get("productCode").toString());

			List<Map<String, Object>> roundLst = new ArrayList<Map<String, Object>>();

			if (productOrder.getApprUserId() > 0) {
				// 审批列表 获取生产通知单信息
				roundLst = productionOrderDao
						.getApprProductorderList(productOrder);
			} else {
				// 查看列表 获取生产通知单信息
				roundLst = productionOrderDao.getProductorderList(productOrder);
			}

			for (Map<String, Object> roundMap : roundLst) {

				String state = roundMap.get("state").toString();

				Date d_overTime = (Date) map.get("overTime");

				if ((new Date()).getTime() - d_overTime.getTime() > 0) {

					outTimeCount++;

					break;

				} else {

					if (!state.equals("5")) {

						if (state.equals("1")) {

							notStartedCount = notStartedCount + 1;

						}
					} else {

						alreadyCompletedCount = alreadyCompletedCount + 1;

					}
				}
			}
			if (outTimeCount > 0) {
				map.put("status", 4);

			} else if (roundLst.size() == notStartedCount) {

				map.put("status", 1);

			} else if (roundLst.size() == alreadyCompletedCount) {

				map.put("status", 3);

			} else {

				map.put("status", 2);

			}

			if (map.get("productName").toString().contains("帮面")) {

				map.put("processName", "帮面生产");

			} else if (map.get("productName").toString().contains("中底")) {

				map.put("processName", "中底生产");

			} else if (map.get("productName").toString().contains("成型底")) {

				map.put("processName", "成型底生产");

			} else if (map.get("productName").toString()
					.equals(map.get("finishedProductName").toString())) {

				map.put("processName", "成品生产");
			}
		}

		return lst;
	}

	@Override
	public int getProductionOrderCount() {

		return productionOrderDao.getProductionOrderCount();
	}

	@Override
	public List queryProductionOrderDetailsList(ProductOrder productOrder) {

		List<Map<String, Object>> lst = productionOrderDao
				.queryProductionOrderDetailsList(productOrder);

		Date overTime = null;

		if (lst != null && lst.size() > 0) {

			for (Map<String, Object> map : lst) {

				Date realOverTime = (Date) map.get("realOverTime");

				if (realOverTime != null) {

					if (overTime != null) {

						if (overTime.compareTo(realOverTime) < 0) {

							overTime = realOverTime;
						}
					} else {

						overTime = realOverTime;
					}
				}

				if (map != null) {

					int kzType = Integer.parseInt(map.get("kzType").toString());

					int stage = Integer.parseInt(map.get("stage").toString());

					if (kzType > 0) {

						map.put("processName", "帮面生产");

					} else if (stage > 0) {

						map.put("processName", "成品生产");

					} else {

						List<Map<String, Object>> processNameList = new ArrayList<Map<String, Object>>();

						int operatorId = Integer.parseInt(map.get("operatorId")
								.toString());

						processNameList = userDao
								.getUserForProcessName(operatorId);

						if (processNameList != null
								&& processNameList.size() > 0) {

							for (Map<String, Object> processNameMap : processNameList) {

								if (processNameMap != null) {
									// TODO
									if (processNameMap.get("processName") == null) {

										processNameList = userDao
												.getUserForProcessNameForTeam(operatorId);

										processNameMap = processNameList.get(0);
									}

									String processName = processNameMap.get(
											"processName").toString();

									if (processName.equals("中底")) {

										map.put("processName", "中底生产");

									} else if (processName.equals("成型底")) {

										map.put("processName", "成型底生产");

									}
								}
							}
						}
					}
				}
			}
			for (Map<String, Object> map : lst) {

				map.put("realOverTime", overTime);
			}
		}

		return lst;
	}

	@Override
	public List getqualityChecksByTime(ProductOrder productOrder) {

		return productionOrderDao.getqualityChecksByTime(productOrder);
	}

	@Override
	public List getqualityChecksByproductNo(String productNo) {

		return productionOrderDao.getqualityChecksByproductNo(productNo);
	}

	@Override
	public List getqualityChecksByNumbers(String numbers) {

		return productionOrderDao.getqualityChecksByNumbers(numbers);
	}

	@Override
	public List getqualityChecksByProcess(String process) {

		return productionOrderDao.getqualityChecksByProcess(process);
	}

	@Override
	public List getProductionOrderByScheduleNo(ProductOrder scheduleNo) {

		return productionOrderDao.getProductionOrderByScheduleNo(scheduleNo);
	}

	@Override
	public List queryProductionOrderParameter(ProductOrder order) {
		List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>();
		// 第一步：查询是否为成品
		List<Map<String, Object>> lstF = productionOrderDao
				.queryProductionOrderParameterFOneStep(order);
		List<Map<String, Object>> lstP = productionOrderDao
				.queryProductionOrderParameterPOneStep(order);
		String flag = "";
		if (lstF != null && lstF.size() > 0) {

			flag = "1";
		} else if (lstP != null && lstP.size() > 0) {

			flag = "2";

		}
		productionOrderDao.queryProductionOrderParameter(order, flag);

		lst = productionOrderDao.queryProductionOrderParameterFOrP(order, flag);

		return lst;
	}

	@Override
	public void splitRound(ProductOrder productOrder) {
		if (productOrder != null) {
			int productCount = productOrder.getProductCount();
			int number = productOrder.getNumber();
			int count1 = productCount - number;// 拆分后剩下的轮次
			productOrder.setProductCount(count1);
			// 更新轮次
			productionOrderDao
					.updateProductionOrderByRoundAndSize(productOrder);

			int count2 = productCount - count1;// 计算拆分出来的轮次数
			int maxRound = productionOrderDao.getMaxRound(productOrder);// 获取最大轮次
			ProductOrder order = productionOrderDao
					.getProductionOrderByRoundAndProductCode(productOrder);
			order.setProductCount(count2);
			order.setRound(maxRound + 1);
			// 增加轮次
			productionOrderDao.insertProductionOrderByRoundAndSize(order);
		}
	}
	@Override
	public void splitRoundByFinished(ProductOrder productOrder) {
		
			productOrder.setId(productOrder.getId());
			
			ProductOrder orderCF = productionOrderDao.getProductionOrderByRoundAndProductCode(productOrder);
			
			orderCF.setProductCount(productOrder.getNumber());
			
			orderCF.setRound(productOrder.getRound()+1);
			// 增加轮次
			productionOrderDao.insertProductionOrderByRoundAndSize(orderCF);
		
	}

	@Override
	public void mergeRound(ProductOrder productOrder) {

		if (productOrder.getIds() != null && !productOrder.getIds().equals("")) {

			Integer[] sort = StringUtil.sort(productOrder.getIds());

			int number = 0;

			productOrder.setId(sort[0]);
			// 查询出要被合并的轮次最小轮次的id
			ProductOrder order = productionOrderDao.getOrderById(productOrder);

			for (Integer i : sort) {

				productOrder.setId(i);

				// 根据id查询出要被合并的轮次信息
				ProductOrder o = productionOrderDao.getOrderById(productOrder);

				// 要被合并的数量
				number = o.getProductCount() + number;

				if (o.getId() > order.getId()) {

					productionOrderDao.deleteProductOrder(o);
				}
			}

			// 合并的总数量
			order.setProductCount(number);

			productionOrderDao.updateProductionOrderByRoundAndSize(order);

			// 查询出所有的轮次 找到被合并轮次
			List<Map<String, Object>> list = productionOrderDao
					.getProductOrderRound(order);
			// 将所有轮次更新
			for (int i = 0; i < list.size(); i++) {

				Map<String, Object> map = list.get(i);

				ProductOrder proOrder = new ProductOrder();

				proOrder.setId(Integer.parseInt(map.get("id").toString()));

				proOrder.setRound(i + 1);

				productionOrderDao.updateProductionOrder(proOrder);

			}
		}
	}

	@Override
	public List<Map<String, Object>> selectProduction(String startTime,
			String endTime) {

		return productionOrderDao.selectProduction(startTime, endTime);
	}

	@Override
	public List selectUserByRoleType() {

		return productionOrderDao.selectUserByRoleType();
	}

	@Override
	public int getUsersTypeCount() {

		return productionOrderDao.getUsersTypeCount();
	}

	@Override
	public ProductOrder getProductionOrderByRound(ProductOrder productOrder) {
		return productionOrderDao.getProductionOrderByRound(productOrder);
	}

	@Override
	public void updateProductionOrder(ProductOrder productOrder) {

		productionOrderDao.updateProductionOrder(productOrder);

	}
	@Override
	public void deleteProductOrderById(ProductOrder order) {
		
		order = productionOrderDao.getOrderById(order);
		
		productionOrderDao.deleteProductOrderById(order);
		
		List<Map<String, Object>> list = productionOrderDao
				.getProductOrderRoundByRoundType(order);
		
		
		int maxRound = productionOrderDao.getMaxRoundFFinished(order);
		// 将所有轮次更新
		for (int i = 0; i < list.size(); i++) {

			Map<String, Object> map = list.get(i);

			ProductOrder proOrder = new ProductOrder();

			proOrder.setId(Integer.parseInt(map.get("id").toString()));

			proOrder.setRound(maxRound + i + 1);

			productionOrderDao.updateProductionOrder(proOrder);

		}
		
	}

	@Override
	public List getqualityChecksByMany(String productCode, String processName,
			String startTime, String endTime) {

		return productionOrderDao.getqualityChecksByMany(productCode,
				processName, startTime, endTime);
	}

	@Override
	public List getPrList() {

		return productionOrderDao.getPrList();
	}

	@Override
	public List selectSizeAndCount(String code) {
		// TODO Auto-generated method stub
		return productionOrderDao.selectSizeAndCount(code);
	}

	@Override
	public List selectCount(String code) {
		// TODO Auto-generated method stub
		return productionOrderDao.selectCount(code);
	}

	@Override
	public ProductOrder getProductionOrderById(ProductOrder productOrder) {

		return productionOrderDao.getProductionOrderById(productOrder);
	}

	@Override
	public List selectProductTeamList() {

		return productionOrderDao.selectProductTeamList();
	}

	@Override
	public ProductOrder getOrderById(ProductOrder productOrder) {

		return productionOrderDao.getOrderById(productOrder);
	}
	@Override
	public ProductOrder getProductionOrderByRoundAndProductCode(ProductOrder productOrder) {
		
		return productionOrderDao.getProductionOrderByRoundAndProductCode(productOrder);
	}

	@Override
	public void updateRoundTypeByProductCode(ProductOrder productOrder) {

		productionOrderDao.updateRoundTypeByProductCode(productOrder);
	}

}
